package com.example.idiom;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;

import android.content.Context;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener{
    private String TAG="chengyu";
    private TableLayout mtable;
    private TextView pinyin;
    private TextView mean;
    private TextView words2;
    private Button btn_words;
    private Button btn_mean;
    private Button btn_search;
    private Button btn_save;
    private View mView_words;
    private View mView_mean;
    private View mView_search;
    private EditText editText;
    private Spinner ideas;

    private AlertDialog alertDialog=null;
    private AlertDialog.Builder builder_words=null;
    private AlertDialog.Builder builder_mean=null;
    private AlertDialog.Builder builder_search=null;

    private Context mcontext;

    private Typeface gudian;
    private Typeface wei;
    private Typeface zihei;
    private Typeface lishu;

    private String words;
    private ArrayList<search> arrayList;
    private BaseAdapter baseAdapter;
    private GetDBFile getDBFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }
    //初始化
    private void init(){
        mtable=findViewById(R.id.words);
        pinyin=findViewById(R.id.pinyin);
        mean=findViewById(R.id.mean);
        words2=findViewById(R.id.words2);
        btn_words=findViewById(R.id.writewords);
        btn_mean=findViewById(R.id.writemean);
        btn_search=findViewById(R.id.search);
        btn_save=findViewById(R.id.save);

        btn_mean.setOnClickListener(this);
        btn_words.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        btn_save.setOnClickListener(this);

        words=getResources().getString(R.string.approve_words);
        words=words.substring(0,words.length()-1);

        write(words);

        mcontext=MainActivity.this;

        gudian= ResourcesCompat.getFont(getApplicationContext(),R.font.hjw);
        wei=ResourcesCompat.getFont(getApplicationContext(),R.font.wei);
        zihei=ResourcesCompat.getFont(getApplicationContext(),R.font.zihei);
        lishu=ResourcesCompat.getFont(getApplicationContext(),R.font.jw);

        pinyin.setTypeface(gudian);
        mean.setTypeface(lishu);
        words2.setTypeface(zihei);

        builder_words=new AlertDialog.Builder(mcontext);
        builder_mean=new AlertDialog.Builder(mcontext);
        builder_search=new AlertDialog.Builder(mcontext);

        mView_words=MainActivity.this.getLayoutInflater().inflate(R.layout.inputwords,null,false);
        mView_mean=MainActivity.this.getLayoutInflater().inflate(R.layout.inputmean,null,false);
        mView_search=MainActivity.this.getLayoutInflater().inflate(R.layout.search_idea,null,false);

        mView_words.findViewById(R.id.push_words).setOnClickListener(this);
        mView_words.findViewById(R.id.push_words_back).setOnClickListener(this);

        mView_search.findViewById(R.id.search_key).setOnClickListener(this);
        mView_search.findViewById(R.id.search_key_back).setOnClickListener(this);

        ideas=mView_search.findViewById(R.id.spinner_idea);

        mView_mean.findViewById(R.id.push_mean).setOnClickListener(this);
        mView_mean.findViewById(R.id.push_mean_back).setOnClickListener(this);

        builder_words.setView(mView_words);
        builder_words.setCancelable(false);

        builder_mean.setView(mView_mean);
        builder_mean.setCancelable(false);

        builder_search.setView(mView_search);
        builder_search.setCancelable(false);

        arrayList=new ArrayList<search>();

        getDBFile=new GetDBFile(mcontext);
        try {
            getDBFile.CopyDBFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //米字格中写字
    private void write(String words){
        int length=words.length();
        int rows=length/6;
        if(rows*6<length) rows+=1;
        int i=0;
        mtable.removeAllViews();
        for(int j=0;j<rows;j++){
            TableRow Row=new TableRow(this);
            if(length<=6){
                Row.setGravity(Gravity.CENTER_HORIZONTAL);
            }
            while (i<length&&i<(j+1)*6){
                View layout= LayoutInflater.from(getApplicationContext()).inflate(R.layout.word,null);
                TextView word=layout.findViewById(R.id.word);
                word.setTypeface(wei);
                word.setText(words.substring(i,i+1));
                Row.addView(layout);
                i++;
            }
            mtable.addView(Row);
        }
    }

    private void write_words2(String words){
        words2.setText(words);
    }

    private void write_mean(String words){
        mean.setText(words);
    }

    private String getpinyin(String words){
        GetPinYin getPinYin=new GetPinYin();
        String P=getPinYin.getFullSpell(words);
        return P;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.writewords:
                alertDialog=builder_words.create();
                alertDialog.show();
            break;
            case R.id.writemean:
                alertDialog=builder_mean.create();
                alertDialog.show();
            break;
            case R.id.push_words:
                editText=mView_words.findViewById(R.id.edit_words);
                String words=editText.getText().toString();
                if(words.length()==0){
                    Toast.makeText(mcontext,"字数不能为零",Toast.LENGTH_SHORT).show();
                }else{
                    write(words);
                    write_words2(words+":");
                    String temp=getpinyin(words);
                    pinyin.setText(temp);
                    ((ViewGroup) mView_words.getParent()).removeView(mView_words);
                    editText.setText("");
                    alertDialog.dismiss();
                }
            break;
            case R.id.push_words_back:
                ((ViewGroup) mView_words.getParent()).removeView(mView_words);
                editText.setText("");
                alertDialog.dismiss();
            break;
            case R.id.push_mean:
                editText=mView_mean.findViewById(R.id.edit_mean);
                String mean=editText.getText().toString();
                if(mean.length()==0){
                    Toast.makeText(mcontext,"字数不能为零",Toast.LENGTH_SHORT).show();
                }else{
                    write_mean("\u3000\u3000"+mean);
                    ((ViewGroup) mView_mean.getParent()).removeView(mView_mean);
                    editText.setText("");
                    alertDialog.dismiss();
                }
                break;
            case R.id.push_mean_back:
                ((ViewGroup) mView_mean.getParent()).removeView(mView_mean);
                editText.setText("");
                alertDialog.dismiss();
                break;
            case R.id.search:
                alertDialog=builder_search.create();
                alertDialog.show();
                break;
            case R.id.search_key:
                editText=mView_search.findViewById(R.id.keys);
                String temp_key=editText.getText().toString();
                String[] temp=temp_key.split(" ");
                temp_key="";
                for(int i=0;i<temp.length;i++){
                    temp_key+=temp[i];
                }
                String temp_pinyin=getpinyin(temp_key);
                addIdea(temp_key,temp_pinyin);
                break;
            case R.id.search_key_back:
                ((ViewGroup)mView_search.getParent()).removeView(mView_search);
                editText.setText("");
                ideas.setAdapter(null);
                alertDialog.dismiss();
                break;
            case R.id.save:
                Toast.makeText(mcontext,"该共能暂时不可用",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void addIdea(String temp_key,String temp_pinyin){
        arrayList.clear();
        String[] pinyins = temp_pinyin.split(" ");
        List<String> temp_keys=new ArrayList<String>();
        for (int i=0;i<temp_key.length();i++){
            String key=temp_key.substring(i,i+1);
            if(key!=" "){
                temp_keys.add(key);
            }
        }
        String database_path=getDatabasePath("chengyu.db").toString();
        SQLiteDatabase database=SQLiteDatabase.openDatabase(database_path,null,SQLiteDatabase.OPEN_READONLY);
        String sql="SELECT * FROM cy\n" +
                "WHERE ((";
          //      "?) AND (?) AND (?) AND (?);";
        String pinyin_1="";
        String pinyin_2="";
        String pinyin_3="";
        String pinyin_4="";
        for(int i=0;i<pinyins.length-1;i++){
            pinyin_1+="\"拼音一\"='"+pinyins[i]+"' OR ";
            pinyin_2+="\"拼音二\"='"+pinyins[i]+"' OR ";
            pinyin_3+="\"拼音三\"='"+pinyins[i]+"' OR ";
            pinyin_4+="\"拼音四\"='"+pinyins[i]+"' OR ";
        }
        pinyin_1+="\"拼音一\"='"+pinyins[pinyins.length-1]+"'";
        pinyin_2+="\"拼音二\"='"+pinyins[pinyins.length-1]+"'";
        pinyin_3+="\"拼音三\"='"+pinyins[pinyins.length-1]+"'";
        pinyin_4+="\"拼音四\"='"+pinyins[pinyins.length-1]+"'";
        try {
            sql+=pinyin_1+") AND ("+pinyin_2+")) OR (("+pinyin_3+") AND ("+pinyin_4+"));";
            SQLiteCursor cursor=(SQLiteCursor) database.rawQuery(sql,null);
            cursor.moveToFirst();
            Log.d(TAG, "addIdea: >>>>>>>>>>>>>>"+Integer.toString(cursor.getCount()));
            if(cursor.getCount()==0){
                Toast.makeText(mcontext,"抱歉找不到相关内容,换一些关键词试试吧",Toast.LENGTH_SHORT).show();
            }
            for(int i=0;i<cursor.getCount();i++){
                String temp=cursor.getString(0).substring(0,4);
                String temp_1=cursor.getString(3);
                String temp_2=cursor.getString(4);
                String temp_3=cursor.getString(5);
                String temp_4=cursor.getString(6);
                cursor.moveToNext();
                Log.d(TAG, "addIdea: >>>>>>>>>>>>>>>"+temp);
                insertidea(temp,temp_1,temp_2,temp_3,temp_4,pinyins,temp_keys);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(arrayList.size()!=0){
            baseAdapter=new chengyuAdapter(arrayList,mcontext);
            ideas.setAdapter(baseAdapter);
            ideas.setOnItemSelectedListener(this);
        }else{
            Toast.makeText(mcontext,"抱歉找不到相关内容,换一些关键词试试吧",Toast.LENGTH_SHORT).show();
        }
    }
    //查询到的成语，拼音1，拼音2，拼音3，拼音4，拼音数组，汉字数组
    public void insertidea(String a,String b,String c,String d,String e,String[] f,List<String> g){
        String new_chengyu="";
        int m=0;
        for(int i=0;i<f.length;i++){
            if(f[i].equals(b)){
                new_chengyu+=g.get(i);
                break;
            }
            if(i==f.length-1){
                new_chengyu+=a.substring(0,1);
                m+=1;
            }
        }
        for(int i=0;i<f.length;i++){
            if(f[i].equals(c)){
                new_chengyu+=g.get(i);
                break;
            }
            if(i==f.length-1){
                new_chengyu+=a.substring(1,2);
                m+=1;
            }
        }
        for(int i=0;i<f.length;i++){
            if(f[i].equals(d)){
                new_chengyu+=g.get(i);
                break;
            }
            if(i==f.length-1){
                new_chengyu+=a.substring(2,3);
                m+=1;
            }
        }
        for(int i=0;i<f.length;i++){
            if(f[i].equals(e)){
                new_chengyu+=g.get(i);
                break;
            }
            if(i==f.length-1){
                new_chengyu+=a.substring(3,4);
                m+=1;
            }
        }
        if(m<2){
            arrayList.add(new search(a,new_chengyu));
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String temp=arrayList.get(position).getNew_chengyu();
        String temp_1=temp.substring(0,4);
        write(temp_1);
        write_words2(temp_1);
        String temp_2=getpinyin(temp_1);
        pinyin.setText(temp_2);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}